package com.useeinfo.oa.modules.wuHanCommon.base.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.AutomaticTable;
import com.useeinfo.oa.modules.wuHanCommon.base.enums.MeterReadingEnum;
import com.useeinfo.oa.modules.wuHanCommon.base.enums.PointSystem;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("AutomaticTableDao")
public class AutomaticTableDao implements CrudDao<AutomaticTable> {
    private final static Logger logger = LoggerFactory.getLogger(AutomaticTableDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {
        Map<String, Object> conditionHash = new HashMap<>();

        conditionHash.put("deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        String number = queryHash.get("number");
        if (StringUtils.isNotBlank(number)) {
            conditionHash.put("number = ?{paramIndex} ", number);
        }
        String checkContent = queryHash.get("checkContent");
        if (StringUtils.isNotBlank(checkContent)) {
            conditionHash.put("wuHanPoint.remark = ?{paramIndex} ", checkContent);
        }
        String meterReading = queryHash.get("meterReading");
        if (StringUtils.isNotBlank(meterReading)) {
            conditionHash.put("wuHanPoint.wuHanUnit.meterReadingEnum = ?{paramIndex} ", MeterReadingEnum.valueOf(meterReading));
        }
        String pointSystem = queryHash.get("pointSystem");
        if (StringUtils.isNotBlank(pointSystem)) {
            conditionHash.put("wuHanPoint.wuHanUnit.pointSystem = ?{paramIndex} ", PointSystem.valueOf(pointSystem));
        }
        String autoTime = queryHash.get("autoTime");
        if (StringUtils.isNotBlank(autoTime)) {
            Date date = StringConverters.ToDateOnly(autoTime);
            conditionHash.put("autoTime >= ?{paramIndex} ", DateTimeUtils.getBeginOfDay(date));
            conditionHash.put("autoTime <= ?{paramIndex} ", DateTimeUtils.getEndOfDay(date));
        }
        String startTime = queryHash.get("startTime");
        if (StringUtils.isNotBlank(startTime)) {
            conditionHash.put("autoTime > ?{paramIndex} ", StringConverters.ToDateTime(startTime));
        }
        String endTime = queryHash.get("endTime");
        if (StringUtils.isNotBlank(endTime)) {
            conditionHash.put("autoTime <= ?{paramIndex} ", StringConverters.ToDateTime(endTime));
        }

        String startDate = queryHash.get("startDate");
        if (StringUtils.isNotBlank(startDate)) {
            conditionHash.put("autoTime >= ?{paramIndex} ", StringConverters.ToDateTime(startDate));
        }
        String endDate = queryHash.get("endDate");
        if (StringUtils.isNotBlank(endDate)) {
            conditionHash.put("autoTime <= ?{paramIndex} ", StringConverters.ToDateTime(endDate));
        }

        String d_startDate = queryHash.get("d_startDate");
        if (StringUtils.isNotBlank(d_startDate)) {
            conditionHash.put("autoTime >= ?{paramIndex} ", DateTimeUtils.getBeginOfDay(StringConverters.ToDateOnly(d_startDate)));
        }
        String d_endDate = queryHash.get("d_endDate");
        if (StringUtils.isNotBlank(d_endDate)) {
            conditionHash.put("autoTime <= ?{paramIndex} ", DateTimeUtils.getEndOfDay(StringConverters.ToDateOnly(d_endDate)));
        }
        String unitId = queryHash.get("unitId");
        if (StringUtils.isNotBlank(unitId)) {
            conditionHash.put("wuHanPoint.wuHanUnit.id = ?{paramIndex} ", StringConverters.ToLong(unitId));
        }

        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(w) from AutomaticTable w ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<AutomaticTable> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select w from AutomaticTable w ", "order by w.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<AutomaticTable> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, AutomaticTable.class);
        return queryParam.findPageList(typedQuery);
    }

    @Override
    public AutomaticTable findModel(Long id) {
        return entityManager.find(AutomaticTable.class, id);
    }

    @Override
    public Integer add(AutomaticTable model) {
        model.setCreateDate(new Date());
        entityManager.persist(model);
        logger.info("WarningCreateAcceptDaoImpl添加WarningCreateAccept成功！");
        return 1;
    }

    @Override
    public Integer update(AutomaticTable model) {
        model.setUpdateDate(new Date());
        entityManager.merge(model);
        return 1;
    }

    @Override
    public Integer delete(Long id) {
        AutomaticTable automaticTable = entityManager.find(AutomaticTable.class, id);
        entityManager.remove(automaticTable);
        return 1;
    }

    @Override
    public Integer deleteLogic(AutomaticTable model) {
        return null;
    }


    //根据id查询结构
    public List getAutomaticTable(Map<String, String> queryHash) {
        String auto_time = queryHash.get("auto_time");
        String yesterday = queryHash.get("yesterday");
        String meter_reading_enum = queryHash.get("meter_reading_enum");
        if (StringUtils.isBlank(auto_time) || StringUtils.isBlank(meter_reading_enum) || StringUtils.isBlank(yesterday)) {
            return null;
        }
        String sql = "SELECT wa.id,wa.check_content,wa.time_index,wa.content_index,\n" +
                "CASE WHEN wa.end_time='00:00:00' THEN (SELECT a.`value` FROM wuhan_automatic_table a\n" +
                "LEFT JOIN wuhan_point b\n" +
                "ON a.point_id=b.id\n" +
                "LEFT JOIN wuhan_unit c\n" +
                "ON b.unit_id=c.id\n" +
                "WHERE 1=1\n" +
                "AND a.auto_time>str_to_date(CONCAT('" + yesterday + " ',wa.start_time),'%Y-%m-%d %H:%i:%s')\n" +
                "AND a.auto_time<=str_to_date(CONCAT('" + auto_time + " ',wa.end_time),'%Y-%m-%d %H:%i:%s')\n" +
                "AND c.meter_reading_enum='" + meter_reading_enum + "'\n" +
                "AND b.remark=wa.check_content\n" +
                "ORDER BY a.auto_time DESC LIMIT 0,1) ELSE (SELECT a.`value` FROM wuhan_automatic_table a\n" +
                "LEFT JOIN wuhan_point b\n" +
                "ON a.point_id=b.id\n" +
                "LEFT JOIN wuhan_unit c\n" +
                "ON b.unit_id=c.id\n" +
                "WHERE 1=1\n" +
                "AND a.auto_time>str_to_date(CONCAT('" + auto_time + " ',wa.start_time),'%Y-%m-%d %H:%i:%s')\n" +
                "AND a.auto_time<=str_to_date(CONCAT('" + auto_time + " ',wa.end_time),'%Y-%m-%d %H:%i:%s')\n" +
                "AND c.meter_reading_enum='" + meter_reading_enum + "'\n" +
                "AND b.remark=wa.check_content\n" +
                "ORDER BY a.auto_time DESC LIMIT 0,1) END as value1\n" +
                "FROM wuhan_automatic_model wa\n" +
                "WHERE wa.meter_reading_enum='" + meter_reading_enum + "'";
        return entityManager.createNativeQuery(sql).getResultList();
    }

}
